<template>
  <div class="answerq">
    <div :class="type != 2 ? 'topic' : 'topicwidth'">
      <div class="top-topic">
        <span style="margin-right: 10px;font-size: 15px;" @click="runturgo"><icon-undo /> </span>
        {{ info.saveName }}
        <span class="timeclass" v-if="type == 2">用时：{{ info.time }} 秒</span>
      </div>
      <div class="Loading" v-if="!test">
        <a-spin dot />
      </div>
      <div class="tijiaoz" v-if="jiazai" >
        <a-spin dot />
      </div>
      <div class="timi" v-for="(item, index) in test" :key="index">
        <!-- <span>{{ item.number }}.</span> -->
        <span class="timi-p">{{ item.id }}.</span>
        <span class="timi-p" v-html="item.test_title"></span>
        <span
          v-if="
            item.if_choose != 1 && item.if_choose != 2 && item.if_choose != 3
          "
          style="color: #fb6d30"
          >本题暂不支持在线作答，请在纸上写上正确答案</span
        >
        <div
          class="timi-listtaxt"
          v-for="(itemlist, subIndex) in item.sub"
          :key="subIndex"
        >
          {{ itemlist.id }}. <span v-html="itemlist.sub_title"></span>
          <span
            v-if="
              itemlist.if_choose != 1 &&
              itemlist.if_choose != 2 &&
              itemlist.if_choose != 3
            "
            style="color: #fb6d30"
            >本题暂不支持在线作答，请在纸上写上正确答案</span
          >
          <div
            class="time-cleck"
            v-for="(itemsdata, optionIndex) in itemlist.sub_options"
            :key="optionIndex"
            @click="
              type != 2
                ? toggleOption(index, subIndex, optionIndex, 'sub')
                : null
            "
          >
            <a-row class="grid-demo">
              <a-col :span="22">
                <div class="col-name" v-html="itemsdata"></div>
              </a-col>
              <a-col :span="2">
                <div class="col-name-right">
                  <icon-check size="25"
                    v-if="isSelected(index, subIndex, optionIndex, 'sub')"
                  />
                  <!-- <icon-close /> -->
                </div>
              </a-col>
            </a-row>
            <!-- </a-space> -->
          </div>
            <div v-if="type == 2 && item.if_choose == 1" class="answerdaan">
            正确答案：<span style="color: #0075ff"
              >{{ itemlist.sub_right_answer.replace(/\r/g, '').replace(/\n/g, ' ').replace(/\s+/g, ' ').trim() }}
            </span>
            您的答案:
            <span style="color: #0aaf60"> {{ itemlist.sub_answer }} &nbsp;</span>
            <span
              :class="
                itemlist.sub_right_answer.replace(/\r/g, '').replace(/\n/g, ' ').replace(/\s+/g, ' ').trim() == itemlist.sub_answer
                  ? 'answerdaan-yes'
                  : 'answerdaan-no'
              "
              >{{
                itemlist.sub_right_answer.replace(/\r/g, '').replace(/\n/g, ' ').replace(/\s+/g, ' ').trim() == itemlist.sub_answer
                  ? "回答正确！"
                  : "回答错误！"
              }}
            </span>
          </div>
          <div class="answer" v-if="itemlist.sub_analytic">
          <div style="margin-top: 24px">
            <div>
              <b style="color: #0075ff">解析 </b>&nbsp;
              <span v-html="itemlist.sub_analytic"></span>
            </div>
            <p class="answer-text-p"></p>
          </div>
        </div>
        </div>
        <div
          class="time-cleck"
          v-for="(items, indexs) in item.test_options"
          :key="indexs"
          @click="type != 2 ? toggleOption(index, null, indexs, 'main') : null"
        >
          <a-row class="grid-demo">
            <a-col :span="22">
              <div class="col-name" v-html="items"></div>
            </a-col>

            <a-col :span="2">
              <div class="col-name-right">
                <icon-check size="22" v-if="isSelected(index, null, indexs, 'main')" />
                <!-- <icon-close /> -->
              </div>
            </a-col>
          </a-row>
          <!-- </a-space> -->
        </div>
        <!--单选题-->
        <div v-if="type == 2 && item.if_choose == 3" class="answerdaan">
          正确答案：<span style="color: #0075ff"
            >{{ item.right_answer.replace(/\r/g, '').replace(/\n/g, ' ').replace(/\s+/g, ' ').trim() }}
          </span>
          您的答案:
          <span style="color: #0aaf60"> {{ item.answer }} &nbsp;</span>
          <span
            :class="
              item.right_answer.replace(/\r/g, '').replace(/\n/g, ' ').replace(/\s+/g, ' ').trim() == item.answer
                ? 'answerdaan-yes'
                : 'answerdaan-no'
            "
            >{{
              item.right_answer.replace(/\r/g, '').replace(/\n/g, ' ').replace(/\s+/g, ' ').trim() == item.answer
                ? "回答正确！"
                : "回答错误！"
            }}
          </span>
        </div>
        <div v-if="type == 2 && item.if_choose == 2" class="answerdaan">
          正确答案：<span style="color: #0075ff"
            >{{ item.right_answer.replace(/\r/g, '').replace(/\n/g, ' ').replace(/\s+/g, ' ').trim() }}
          </span>
          您的答案:
          <span style="color: #0aaf60"> {{ item.answer.replace(/,/g, '') }} &nbsp;</span>
          <span
            :class="
              item.right_answer.replace(/\r/g, '').replace(/\n/g, ' ').replace(/\s+/g, ' ').trim() == item.answer.replace(/,/g, '')
                ? 'answerdaan-yes'
                : 'answerdaan-no'
            "
            >{{
              item.right_answer.replace(/\r/g, '').replace(/\n/g, ' ').replace(/\s+/g, ' ').trim() == item.answer.replace(/,/g, '')
                ? "回答正确！"
                : "回答错误！"
            }}
          </span>
        </div>

        <div class="answer" v-if="type == 2 && item.analytic">
          <div style="margin-top: 24px">
            <div>
              <b style="color: #0075ff">解析 </b>&nbsp;
              <span v-html="item.analytic"></span>
            </div>
            <p class="answer-text-p"></p>
          </div>
        </div>
      </div>
    </div>

    <div class="topic-center" v-if="type != 2">
      <div class="topic-righr">
        <div class="topicon">
          <img src="/img/bianzu.png" style="width: 10px; height: 10px" alt="" />
          答题卡
        </div>
        <div class="topicon">
          计时: <span class="spantext">{{ displayTime }}</span>
        </div>
      </div>

      <div class="xuanxiang" v-for="typeItem in typelist" :key="typeItem">
        <div>{{ typeItem.typeName }}</div>
        <div class="radio">
          <div v-for="(parentItem, parentIndex) in test" :key="parentIndex">
            <div class="radio" v-if="typeItem.typeID == parentItem.test_type">
              <div
                v-for="(subItem, subIndex) in parentItem.sub"
                :key="subIndex"
              >
                <div
                  class="radio-chebok"
                  :class="{
                    selected:
                    isSubQuestionAnswered(parentIndex,subIndex) &&
                      [1, 2, 3, '1', '2', '3'].includes(parentItem.if_choose),
                    'current-question':
                      currentQuestion?.parentIndex === parentIndex &&
                      currentQuestion?.subIndex === parentIndex,
                    'radio-chebok-red': ![1, 2, 3, '1', '2', '3'].includes(
                      subItem.if_choose
                    ),
                  }"
                  @click="scrollToQuestion(parentIndex, subIndex)"
                >
                  <span> {{ subItem.id }}</span>  
                </div>
              </div>

              <div
                class="radio-chebok"
                v-if="!parentItem.sub"
                :class="{
                  selected:
                    isMainQuestionAnswered(parentIndex) &&
                    [1, 2, 3, '1', '2', '3'].includes(parentItem.if_choose),
                  'current-question':
                    currentQuestion?.parentIndex === parentIndex,
                  'radio-chebok-red': ![1, 2, 3, '1', '2', '3'].includes(
                    parentItem.if_choose
                  ), // 新增条件：如果不是1/2/3，则添加disabled类
                }"
                @click="scrollToQuestion(parentIndex)"
              >
                <span> {{ parentItem.id }} </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="row-button">
        <a-row class="grid-demo">
          <a-col :span="6"> </a-col>
          <a-col :span="8">
            <a-button class="buttom" type="outline" @click="submit"
              >提交作答</a-button
            >
          </a-col>
          <a-col :span="8">
            <a-button @click="runturgo">退出测评</a-button>
          </a-col>
          <a-col :span="2"> </a-col>
        </a-row>
      </div>
    </div>
  </div>

  <a-modal
    v-model:visible="visiblelist"
    class="visible"
    width="50vw"
    modalClass="liatname"
  >
    <template #title>
      <div class="liatname">退出作答</div>
    </template>
    <div class="liatname">
      答题暂未完成 是否 退出作答
    </div>
    <template #footer>
      <a-row justify="center">
        <a-col :span="10" style="text-align: center">
          <a-button class="bouutnli" type="primary" @click="handleOkquestions">是</a-button>
        </a-col>
        <a-col :span="10" style="text-align: center">
          <a-button  class="bouutnli" @click="handleCancel">否</a-button>
        </a-col>
      </a-row>
    </template>
  </a-modal>

</template>

<script lang="ts" setup>
import { Message, Modal } from "@arco-design/web-vue";
import { ref, reactive, onMounted, onUnmounted, computed, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  MyHomeworkdocCorrect,
  postMyHomeworkdoAnswer,
  postMyHomeworkdoSubmit,
  postMyHomeworkgetTest,
} from "@/api/measure";
import { Recordrecorderr } from "@/api/Examination";
import { MyHomeworkreturnTestList } from "@/api/diagnosis";
import { RecordwrongDocTest } from "@/api/practise";
import { HomeStatisticspracticeToday } from "@/api/home";
const jiazai = ref(false)
const visiblelist = ref(false)
// 类型定义
type OptionType = "main" | "sub";
type TestItem = {
  test_title: string;
  sub?: SubItem[];
  test_options?: string[];
};

type SubItem = {
  id: string;
  sub_title: string;
  sub_options: string[];
};
let timerInterval: ReturnType<typeof setInterval>;
// 计算显示时间（时+分钟+秒）
const displayTime = computed(() => {
  const hours = Math.floor(realTime.value / 3600);
  const minutes = Math.floor((realTime.value % 3600) / 60);
  const seconds = realTime.value % 60;
  const formattedMinutes = minutes.toString().padStart(2, "0");
  const formattedSeconds = seconds.toString().padStart(2, "0");

  if (hours > 0) {
    return `${hours}小时${formattedMinutes}分钟${formattedSeconds}秒`;
  } else if (minutes > 0) {
    return `${minutes}分钟${formattedSeconds}秒`;
  } else {
    return `${formattedSeconds}秒`;
  }
});
// 计时器相关
const realTime = ref(0);
const type = ref(); //判断是详情还是什么
// let timerInterval: ReturnType<typeof setInterval>;
// 开始计时
const startTimer = () => {
  timerInterval = setInterval(() => {
    realTime.value++;
  }, 1000);
};
// 停止计时
const stopTimer = () => {
  clearInterval(timerInterval);
};
const handleOkquestions = () => {
  router.back();
  visiblelist.value =false
}
const handleCancel = () => {
  visiblelist.value =false
}
// 响应式状态
const selectedOptions = ref<Record<string, boolean>>({});
// 生成唯一标识符
const getOptionKey = (
  parentIndex: number,
  subIndex: number | null,
  optionIndex: number,
  type: OptionType
): string => {
  return `${parentIndex}-${type}-${subIndex ?? "null"}-${optionIndex}`;
};
const form = reactive({
  answer_id: "",
  realTime: 0, //时间currentSub.id,
  answer_num: "",
  anwser_right: false,
  answer: [],
});
// 切换选项状态
const toggleOption = (
  parentIndex: number,
  subIndex: number | null,
  optionIndex: number,
  type: OptionType
) => {
  // 1. 获取当前题目数据
  const question = test.value[parentIndex];
  const isSubQuestion = type === "sub";
  const optionText = isSubQuestion
    ? question.sub?.[subIndex!]?.sub_options[optionIndex]
    : question.test_options?.[optionIndex];

  // 2. 获取当前操作的sub对象（如果是子题目）

  let currentSub = null;
 

  // 1. 生成当前问题的唯一前缀（用于识别同组选项）
  const questionPrefix = `${parentIndex}-${type}-${subIndex ?? "null"}`;
 
  if (question.if_choose === 3) {
    // 单选逻辑
    // 清除同组所有已选选项
    Object.keys(selectedOptions.value).forEach((key) => {
      if (key.startsWith(questionPrefix)) {
        selectedOptions.value[key] = false;
      }
    });
    // 设置当前选项为选中状态
    const currentKey = getOptionKey(parentIndex, subIndex, optionIndex, type);
    selectedOptions.value[currentKey] = true;
    if (isSubQuestion && subIndex !== null) {
      currentSub = question.sub?.[subIndex];
      
      // 2. 获取选项文本
      (form.answer_id = currentSub.answer_id),
        (form.realTime = realTime.value), //时间currentSub.id,
        (form.answer_num = currentSub.id),
        (form.anwser_right = true),
        (form.answer = optionText[0] || "");
      postMyHomeworkdoAnswer(form).then((res: any) => {});
    } else {
     
      currentSub = question.test_options;
      // console.log("当前操作的sub对象:", currentSub[optionIndex]);
      const match = currentSub[optionIndex].match(/^([A-Za-z])/);
      const firstChar = match ? match[1] : "";
      //  console.log(firstChar,'???')
      (form.answer_id = question.answer_id),
        (form.realTime = realTime.value), //时间currentSub.id,
        (form.answer_num = question.number),
        (form.anwser_right = true),
        (form.answer = firstChar);
      postMyHomeworkdoAnswer(form).then((res: any) => {});
    }
  } else if (question.if_choose === 2) {
    // 多选逻辑
    const currentKey = getOptionKey(parentIndex, subIndex, optionIndex, type);
    // 再次点击时取反
    selectedOptions.value[currentKey] = !selectedOptions.value[currentKey];
    // console.log(selectedOptions.value[currentKey], "?");
    if (isSubQuestion && subIndex !== null) {
      currentSub = question.sub?.[subIndex];
     

      const selectedAnswers = [] as any;
      currentSub?.sub_options.forEach((option: any, idx: any) => {
        const optionKey = getOptionKey(parentIndex, subIndex, idx, type);
        
        if (selectedOptions.value[optionKey]) {
          const match = option.match(/^([A-Za-z])/); // 提取选项字母（A/B/C/D）
          if (match) selectedAnswers.push(match[1]);
        }
      });
      // 2. 获取选项文本
      (form.answer_id = currentSub.answer_id),
        (form.realTime = realTime.value), //时间currentSub.id,
        (form.answer_num = currentSub.id),
        (form.anwser_right = true),
        (form.answer = optionText[0] || "");
      postMyHomeworkdoAnswer(form).then((res: any) => {});
      // // 2. 获取选项文本
      // (form.answer_id = currentSub.answer_id),
      //   (form.realTime = realTime.value), //时间currentSub.id,
      //   (form.answer_num = currentSub.id),
      //   (form.anwser_right = false),
      //   (form.answer = optionText[0] || "");
      // postMyHomeworkdoAnswer(form).then((res: any) => {});
    } else {
      currentSub = question.test_options;
      const selectedAnswers = [] as any;
      currentSub?.forEach((option: any, idx: any) => {
        const optionKey = getOptionKey(parentIndex, subIndex, idx, type);
        
        if (selectedOptions.value[optionKey]) {
          const match = option.match(/^([A-Za-z])/); // 提取选项字母（A/B/C/D）
          if (match) selectedAnswers.push(match[1]);
        }
      });
      // console.log(selectedAnswers,'????多选第一层?')
      // console.log(currentSub,'????多选第一层?')
      // console.log("当前操作的sub对象:", currentSub[optionIndex]);
      // const match = currentSub[optionIndex].match(/^([A-Za-z])/);
      // const firstChar = match ? match[1] : "";
      // //  console.log(firstChar,'???')
      (form.answer_id = question.answer_id),
        (form.realTime = realTime.value), //时间currentSub.id,
        (form.answer_num = question.number),
        (form.anwser_right = true),
        (form.answer = selectedAnswers), // 如 "A,C" 表示选中A和C);
        postMyHomeworkdoAnswer(form).then((res: any) => {});
    }
  } else if (question.if_choose === 1) {
    // // 多选逻辑
    if (question.sub?.[subIndex].if_choose == 2) {
      const currentKey = getOptionKey(parentIndex, subIndex, optionIndex, type);
      // 再次点击时取反
      selectedOptions.value[currentKey] = !selectedOptions.value[currentKey];
      // console.log(selectedOptions.value[currentKey], "?");
      if (isSubQuestion && subIndex !== null) {
        currentSub = question.sub?.[subIndex];
       

        // 3. 获取所有选中的选项（多选需要提交多个选项）
        const selectedAnswers = [] as any;
        currentSub.sub_options?.forEach((option, idx) => {
          const optionKey = getOptionKey(parentIndex, subIndex, idx, type);
          if (selectedOptions.value[optionKey]) {
            const match = option.match(/^([A-Za-z])/); // 提取选项字母（A/B/C/D）
            if (match) selectedAnswers.push(match[1]);
          }
        });
        // console.log(selectedAnswers, "????多选第一层?");
        // // 2. 获取选项文本
        (form.answer_id = currentSub.answer_id),
          (form.realTime = realTime.value), //时间currentSub.id,
          (form.answer_num = currentSub.id),
          (form.anwser_right = true),
          (form.answer = selectedAnswers);
        postMyHomeworkdoAnswer(form).then((res: any) => {});
      } else {
        currentSub = question.test_options;
        const selectedAnswers = [] as any;
        currentSub?.forEach((option: any, idx: any) => {
          const optionKey = getOptionKey(parentIndex, subIndex, idx, type);
          // console.log(selectedOptions.value[optionKey], "???");
          if (selectedOptions.value[optionKey]) {
            const match = option.match(/^([A-Za-z])/); // 提取选项字母（A/B/C/D）
            if (match) selectedAnswers.push(match[1]);
          }
        });
        // console.log(selectedAnswers,'????多选第一层?')
        // console.log(currentSub,'????多选第一层?')
        // console.log("当前操作的sub对象:", currentSub[optionIndex]);
        // const match = currentSub[optionIndex].match(/^([A-Za-z])/);
        // const firstChar = match ? match[1] : "";
        // //  console.log(firstChar,'???')
        (form.answer_id = question.answer_id),
          (form.realTime = realTime.value), //时间currentSub.id,
          (form.answer_num = question.number),
          (form.anwser_right = true),
          (form.answer = selectedAnswers), // 如 "A,C" 表示选中A和C);
          postMyHomeworkdoAnswer(form).then((res: any) => {});
      }
    } else if (question.sub?.[subIndex].if_choose == 3) {
      // 单选逻辑
      // 清除同组所有已选选项
      Object.keys(selectedOptions.value).forEach((key) => {
        if (key.startsWith(questionPrefix)) {
          selectedOptions.value[key] = false;
        }
      });
      // 设置当前选项为选中状态
      const currentKey = getOptionKey(parentIndex, subIndex, optionIndex, type);
      selectedOptions.value[currentKey] = true;
      if (isSubQuestion && subIndex !== null) {
        currentSub = question.sub?.[subIndex];
        // console.log("当前操作的sub对象:", currentSub[optionIndex]);
        // 2. 获取选项文本
        (form.answer_id = currentSub.answer_id),
          (form.realTime = realTime.value), //时间currentSub.id,
          (form.answer_num = currentSub.id),
          (form.anwser_right = true),
          (form.answer = optionText[0] || "");
        postMyHomeworkdoAnswer(form).then((res: any) => {});
      } else {
        // console.log(question, "这是数学吗");
        currentSub = question.test_options;
        // console.log("当前操作的sub对象:", currentSub[optionIndex]);
        const match = currentSub[optionIndex].match(/^([A-Za-z])/);
        const firstChar = match ? match[1] : "";
        //  console.log(firstChar,'???')
        (form.answer_id = question.answer_id),
          (form.realTime = realTime.value), //时间currentSub.id,
          (form.answer_num = question.number),
          (form.anwser_right = true),
          (form.answer = firstChar);
        postMyHomeworkdoAnswer(form).then((res: any) => {});
      }
    }
  }
  // 4. 更新当前题目位置（用于答题卡高亮）
  currentQuestion.value = {
    parentIndex,
    subIndex: type === "sub" ? subIndex : undefined,
  };
};
// 检查选中状态
const isSelected = (
  parentIndex: number,
  subIndex: number | null,
  optionIndex: number,
  type: OptionType
): boolean => {
  const key = getOptionKey(parentIndex, subIndex, optionIndex, type);
  return !!selectedOptions.value[key];
};
interface CurrentQuestion {
  parentIndex: number;
  subIndex?: number;
}
// 答题卡状态检查方法（使用计算属性优化）
const currentQuestion = ref<CurrentQuestion | null>(null);
// 子题目检测
const isSubQuestionAnswered = (parentIndex: number, subIndex: number) => {
  // 调试输出
  // console.log(`检查子题目状态: parent=${parentIndex}, sub=${subIndex}`);
  // console.log("1112", parentIndex);
  // console.log("1112", subIndex);
  const parentQuestion = test.value[parentIndex];
  if (!parentQuestion?.sub) return false;
  // console.log("456466", parentQuestion);
  const subQuestion = parentQuestion.sub[subIndex];
  if (!subQuestion?.sub_options) return false;
  // console.log(subQuestion, "?456");

  return subQuestion.sub_options.some((_, optionIndex) => {
    const key = getOptionKey(parentIndex, subIndex, optionIndex, "sub");
    const isSelected = !!selectedOptions.value[key];
    // console.log(`选项 ${optionIndex} 状态:`, isSelected);
    // console.log(`选项 ${optionIndex} 状态:`, selectedOptions.value[key], "?");
    return isSelected;
  });
};
// 验证所有小题是否都有选项被选中
// 验证所有小题是否都有选项被选中，并打印状态
const areAllSubQuestionsAnswered = () => {
  let allAnswered = true;
  for (let parentIndex = 0; parentIndex < test.value.length; parentIndex++) {
    const parentQuestion = test.value[parentIndex];
    //  小题验证
    // console.log(parentQuestion, "?小题?");
    // 只检查 if_choose 是 1、2、3 的题目（包括字符串 '1'、'2'、'3'）
    const shouldCheck = [1, 2, 3, "1", "2", "3"].includes(
      parentQuestion.if_choose
    );
    if (!shouldCheck) continue; // 跳过不需要验证的题目
    if (parentQuestion.sub) {
      const subKeys = Object.keys(parentQuestion.sub);
      for (let i = 0; i < subKeys.length; i++) {
        const subIndex = parseInt(subKeys[i], 10);
        const answered = isSubQuestionAnswered(parentIndex, subIndex);
        if (answered) {
          console.log(
            `主题目索引 ${parentIndex}，子题目索引 ${subIndex} 已被选中`
          );
        } else {
          console.log(
            `主题目索引 ${parentIndex}，子题目索引 ${subIndex} 未被选中`
          );
          allAnswered = false;
        }
      }
    }
  }
  return allAnswered;
};
// 主题目检测
const isMainQuestionAnswered = (parentIndex: number) => {
  const parentItem = test.value[parentIndex];
  // console.log(parentItem, "?主题验证?");

  const shouldCheck = [1, 2, 3, "1", "2", "3"].includes(parentItem?.if_choose);
  if (!shouldCheck) return true;

  return (
    parentItem?.test_options?.some((_, optionIndex) => {
      const key = getOptionKey(parentIndex, null, optionIndex, "main");
      return selectedOptions.value[key];
    }) ?? false
  );
};
// const isMainQuestionAnswered = (parentIndex: number) => {
//   console.log(parentIndex, "???444");
//   return answeredStatus.value.main[parentIndex] ?? false;
// };
const route = useRoute();
const ctrID = reactive({
  ctrID: "",
  textId: "",
});
const router = useRouter();

const info = reactive({
  aatTestStyle: "",
  isContainHearing: "",
  jumpUrl: "",
  saveName: "",
  time: "",
});
const test = ref();
const typelist = ref();
const runturgo = () => {
  if(type.value == 2){
    router.back();
  }else{
    visiblelist.value = true
  }
};

const getTest = () => {
  postMyHomeworkgetTest(ctrID).then((res: any) => {
    info.saveName = res.list.info.saveName;
    realTime.value=res.list.info.time
    typelist.value = res.list.type;
    addSequentialIds(res.list.test);
    startTimer();
  });
};

function addSequentialIds(dataArray: any) {
  let counter = 1; // 全局计数器
  dataArray.forEach((data: any,parentIndex: number) => {
   
   // 初始化主题目的选中状态
   if (data.answer && data.test_options) {
      // 处理单选或多选的主题目
      const isMultiple = data.if_choose == 2 || data.if_choose == '2';
      const answers = isMultiple ? data.answer : [data.answer]; // 如多选可能是 "AC" 或 "A,C"
      
      data
.test_options.forEach((option: string, optionIndex: number) => {
        // 提取选项字母（如 "A.1" -> "A"）
        const optionLetter = option.charAt(0); // 直接取第一个字符就是选项字母
        if (answers.includes(optionLetter)) {
          const key = getOptionKey(parentIndex, null, optionIndex, 'main');
          selectedOptions
.value[key] = true;
        }
      });
    }

    if (data.if_choose === 1) {
      // 复合题：遍历所有小题，并编号
      const processSub = (currentSub: any) => {
        Object.keys(currentSub).forEach((key) => {
          const item = currentSub[key];
          item.id = counter++; // 分配编号并递增
          if (item.sub) {
            processSub(item.sub); // 递归处理更深层的小题（如果有）
          }
        });
      };
      processSub(data.sub); // 处理当前复合题的小题
    } else {
      // 独立题：直接分配编号
      data.id = counter++;
    }
  });
  // console.log(dataArray, "处理后的数据");
  test.value = dataArray;
  typelist.value.map((item) => {
    const demos = test.value.find((items) => {
      return items.test_type == item.typeID
    })
    if(demos.sub != undefined){
      return item.firstd = demos.sub[1].id
    }
  })
  typelist.value.sort(function(a,b){return a.firstd - b.firstd})
  return dataArray;
}
//提交作答
const doSubmit = reactive({
  testRecordID: "",
  realTime: "",
});

// 新增提交时的检查函数
const checkAllAnswered = () => {
  if (!test.value || !Array.isArray(test.value)) {

    return false;
  }

  // 检查所有题目是否完成
  const allAnswered = test.value.every((parentItem, parentIndex) => {
    // 处理子题目
  
    if (parentItem.sub) {
      return areAllSubQuestionsAnswered();
    }
    // 处理主题目
    else {
      return isMainQuestionAnswered(parentIndex);
    }
  });

  return allAnswered;
};
const submit = () => {
  const allAnswered = checkAllAnswered(); // 只在提交时检查
  
  if (allAnswered) {
    doSubmit.realTime = realTime.value;
    if (route.query.textId) {
      doSubmit.testRecordID = route.query.textId as string;
    }
    jiazai.value = true
   
    postMyHomeworkdoSubmit(doSubmit).then((res: any) => {
      if (type.value == 1 || type.value == 2) {
        const ctrID = route.query.ctrID == undefined ? route.query.CTRID : route.query.ctrID;
        if(ctrID == 0){
          Message.success("提交完成");
          jiazai.value = false
          router.go(-1);
        }else{
          MyHomeworkdocCorrect({ ctrID: ctrID as string }).then(
          (res: any) => {
            // push.改变
            localStorage.setItem("index", String(3));
            router.push({
              path: "/Diagnosis",
              query: {},
            });
            jiazai.value = false
            Message.success("提交完成");
          }
        );
        }
        
      } else {
        Message.success("提交完成");
        jiazai.value = false
        router.go(-1);
      }
    });
  } else {
    Message.error("请作答全部题目");
  }
  // console.log(!isAllAnswered.value, "??shishenm");
  // postMyHomeworkdoSubmit(doSubmit).then((res: any) => {});
};
const scrollToQuestion = (parentIndex: number, subIndex?: number) => {
  // 更新当前题目状态
  currentQuestion.value = {
    parentIndex,
    subIndex,
  };

  // 使用 nextTick 确保 DOM 已更新
  nextTick(() => {
    // 获取对应题目的 DOM 元素
    const questionElement = document.querySelectorAll(".timi")[parentIndex];
    const questionElementtop = document.querySelectorAll("imi-p")[parentIndex];

    if (questionElement) {
      // 平滑滚动到题目位置
      questionElement.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });

      // 如果是子题目，可以进一步高亮
      if (subIndex !== undefined) {
        // 这里可以添加子题目高亮逻辑
      
        const subElements = questionElement.querySelectorAll(".time-cleck");
        const subElementscleck =
          questionElement.querySelectorAll(".time-cleck");
      
        if (subElements[subIndex]) {
          // 微调滚动位置，确保子题目在可视区域
          setTimeout(() => {
            subElements[subIndex].scrollIntoView({
              behavior: "smooth",
              block: "center",
            });
          }, 300); // 等待父题目滚动完成
        }
      }
    }
  });
};

//详情
const formtestid = reactive({
  testId: "",
});
const returnTestList = () => {
  MyHomeworkreturnTestList(formtestid).then((res: any) => {
    info.saveName = res.style;
    info.time = res.rtime;
    addSequentialIds(res.test);
  });
};

// 考进 type 3
const ksendForm = reactive({
  subjectId: 0, // 学科id
  docId: 0,
});
const Recorist = () => {
  Recordrecorderr(ksendForm).then((res: any) => {
    // info.saveName = res.list.info.saveName;
    doSubmit.testRecordID = res.list.textRecordId;
    typelist.value = res.list.type;
    addSequentialIds(res.list.test);
    startTimer();
  });
};
//kao
//每日练习
const wrongDocTest = reactive({
  subid: 0, //学科id
  klid: 0, //知识点id
});
const dailypractice = () => {
  RecordwrongDocTest(wrongDocTest).then((res: any) => {
    typelist.value = res.list.type;
    doSubmit.testRecordID = res.list.textRecordId;
    addSequentialIds(res.list.test);
    startTimer();
  });
};
//home 开始练习
const datahome = reactive({
  subjectid: 0, //学科id
  klid: 0, //知识点id
});
const homedata = () => {
  HomeStatisticspracticeToday(datahome).then((res: any) => {
    typelist.value = res.list.type;
    doSubmit.testRecordID = res.list.textRecordId;
    addSequentialIds(res.list.test);
    startTimer();
  });
};

onMounted(() => {
  type.value = route.query.type as string;
  if (type.value == 1) {
    // (info.saveName = route.query.saveName as string),
    ctrID.ctrID = route.query.ctrID as string;
    ctrID.textId = route.query.textId as string;
    getTest(); //获取数据
  } else if (type.value == 2) {
    formtestid.testId = route.query.TestID as string;
    returnTestList();
  } else if (type.value == 3) {
    (info.saveName = route.query.saveName as string),
      (ksendForm.docId = Number(route.query.DocID));
    ksendForm.subjectId = Number(route.query.subjectID);
    Recorist();
  } else if (type.value == 4) {
    (info.saveName = route.query.saveName as string),
      (wrongDocTest.klid = Number(route.query.klID));
    wrongDocTest.subid = Number(route.query.subjectID);
    dailypractice();
  } else if (type.value == 5) {
    (info.saveName = route.query.saveName as string),
      (datahome.klid = Number(route.query.klID));
    datahome.subjectid = Number(route.query.subjectID);
    homedata();
  } else if (type.value == 9) {
    ctrID.ctrID = route.query.CTRID as string;
    ctrID.textId = route.query.textId as string;
    // doSubmit.testRecordID
    getTest(); //获取数据

  }
});
// 页面卸载时停止计时
onUnmounted(() => {
  stopTimer();
});
</script>

<style lang="less" scoped>
.tijiaoz{
  position: absolute;
  left: 40%;
  top: 40%;
  // width: 100px;
  // height: 100px;
}
.answerq {
  // padding: 24px;
  position: relative;
  display: flex;

  .returngo {
    position: absolute;
    cursor: pointer;
    left: 0;
    top: -81px;
  }
  background: #f7fbff;
  .topic {
    padding: 0 24px;
    width: 60vw;
    margin-right: 24px;
    overflow: auto;
    /* WebKit 浏览器（Chrome、Safari） */
    scrollbar-width: none;
    -ms-overflow-style: none;
    height: 85vh;
    // background-color: #fff;
    .top-topic {
      height: 5rem;
      line-height: 81px;
      padding: 0 1vw;
      font-weight: bold;
      font-size: 1.1vw;
      color: #03305c;
      border-bottom: 1px solid #ededed;
      background-color: #fff;
    }
  }
  .timeclass {
    font-size: 14px;
    color: #03305c;
    text-align: right;
  }
  .topicwidth {
    padding: 0 24px;
    width: 100vw;
    // margin-right: 24px;s
    overflow: auto;
    /* WebKit 浏览器（Chrome、Safari） */
    scrollbar-width: none;
    -ms-overflow-style: none;
    height: 85vh;
    // background-color: #fff;
    .top-topic {
      height: 5rem;
      line-height: 81px;
      padding: 0 1vw;
      font-weight: bold;
      font-size: 16px;
      color: #03305c;
      border-bottom: 1px solid #ededed;
      background-color: #fff;
    }
  }
  .xuanxiang {
    margin-top: 24px;

    // background-color: #fff;
  }
  .topic-center {
    width: 30vw;
    padding: 0 24px;
    background-color: #fff;
  }
  .topic-righr {
    height: 81px;
    padding: 0 1vw;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #ededed;
    font-weight: bold;
    font-size: 14px;
    color: #03305c;
    .topicon {
      line-height: 81px;
      font-size: 14px;
      color: #03305c;
      .spantext {
        font-weight: 500;

        color: #fb6d30;
      }
    }
  }
}
.timi {
  margin-top: 24px;
  padding: 0vw 1vw 1vw;
  // height: 100%;
  overflow: auto;
  /* WebKit 浏览器（Chrome、Safari） */
  scrollbar-width: none;
  -ms-overflow-style: none;
  background-color: #fff;
  // height: 75vh;
  .timi-p {
    font-family: DINAlternate, DINAlternate;
    font-weight: 500;
    font-size: 1.1vw;
    color: #03305c;
    margin-top: 1vw;
    line-height: 32px;
    text-align: left;
    font-style: normal;
  }
  .timi-listtaxt {
    margin: 1vw 0;
    color: #03305c;
    font-size: 1.1vw;
  }
}
.time-cleck-green {
  width: 50%;
  background: #e6f7ef;
  border: 1px solid #0aaf60;
  font-weight: 400;
  font-size: 1vw;
  // height: 54px;
  margin-top: 10px;
  // line-height: 54px;
  padding: 1vw;
  color: #0aaf60;
}
.time-cleck-red {
  width: 50%;
  background: rgba(255, 85, 85, 0.1);
  border: 1px solid #ff5555;
  font-weight: 400;
  font-size: 1vw;
  // height: 54px;
  margin-top: 10px;
  // line-height: 54px;
  padding: 1vw;
  color: #ff5555;
}
.time-cleck-nube {
  width: 50%;
  // display: flex;
  margin-top: 10px;
  background: #f7fbff;
  // height: 54px;
  // line-height: 54px;
  padding: 1vw;
  width: 50%;
}
.time-cleck {
  width: 50%;
  // display: flex;
  height: 100%;
  margin-top: 10px;
  // line-height: 54px;
  padding: 1vw;
  font-weight: 400;
  font-size: 1vw;
  color: #0075ff;
  // display: flex;
  // background: rgba(0, 117, 255, 0.1);
  border-radius: 4px;
  border: 1px solid #0075ff;
}
.time-span {
  margin: 0 19px;
}
.answerdaan-yes {
  color: #0aaf60;
  font-size: 14px;
}
.answerdaan-no {
  color: #ff5555;
  font-size: 14px;
}
.time-list {
  // width: 30px;
  // background-color: pink;
  // height: 30px;
  // padding: 24px;
  margin: 0px 0 0 15px;
}
.radio {
  display: flex;
  // justify-content: space-between;
  font-size: 14px;
  flex-wrap: wrap; /* 允许元素自动换行 */
  width: 100%;
  // background-color: pink;
  // gap: 10px; /* 元素之间的间距 */
  // justify-content: ;
}
.radio-chebok {
  width: 46px;
  height: 46px;
  border: 1px solid #0075ff;
  color: #0075ff;
  margin: 20px 20px 0 0;

  text-align: center;
  line-height: 46px;
  border-radius: 23px;
}
.radio-chebok.selected {
  background-color: #0075ff;
  color: white;
  border-color: #0075ff;
}
.radio-chebok-one {
  width: 46px;
  height: 46px;
  text-align: center;
  line-height: 46px;
  border: 1px solid #0075ff;
  background: #0075ff;
  color: #ffffff;
  margin: 20px 20px 0 0;
  border-radius: 23px;
}
.radio-chebok-text {
  width: 46px;
  height: 46px;
  text-align: center;
  line-height: 46px;
  border: 1px solid #f7fbff;
  background: #f7fbff;
  color: #8393a3;
  margin: 20px 20px 0 0;
  border-radius: 23px;
}
.radio-chebok-red {
  width: 46px;
  height: 46px;
  text-align: center;
  line-height: 46px;
  border: 1px solid #8393a3;
  background: #e9e5e5;
  // font-weight: 500;
  // font-size: 18px;
  color: #8393a3;
  margin: 20px 20px 0 0;
  border-radius: 23px;
}
.radio-chebok-green {
  width: 46px;
  height: 46px;
  text-align: center;
  line-height: 46px;
  border: 1px solid #0aaf60;
  background: #e6f7ef;
  // font-weight: 500;
  // font-size: 18px;
  color: #0aaf60;
  margin: 20px 20px 0 0;
  border-radius: 23px;
}
.radio-chebok-three {
  width: 46px;
  height: 46px;
  text-align: center;
  line-height: 46px;
  border: 1px solid #f7fbff;
  background: #f7fbff;
  color: #03305c;
  margin: 20px 20px 0 0;
  border-radius: 23px;
}
.row-button {
  margin-top: 30px;
}
.col-name {
  text-align: left;
  color: #03305c;
  // background-color: pink;
}
.col-name-right {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.answer {
  font-weight: 700;
  // background-color: #f7fbff;
  font-size: 14px;
  color: #03305c;
}
.answer-text-p {
  font-weight: 400;
  font-size: 14px;
  margin-top: 8px;
  color: rgba(3, 48, 92, 0.9);
  line-height: 21px;
}
.answerdaan {
  font-size: 14px;
  padding: 10px 0;
  color: #03305c;
}
.liatname{
  text-align: center;
}
@media (max-width: 768px) {
  .answer-text-p {
    font-weight: 400;
    font-size: 0.8vw;
    margin-top: 4px;
    color: rgba(3, 48, 92, 0.9);
    line-height: 15px;
  }
  .bouutnli{
    width: 5vw;
  }
  .col-name {
  text-align: left;
  color: #03305c;
  font-size: 3vw;
  // background-color: pink;
}
  .timi-listtaxt {
    margin: 1vw 0;
    color: #03305c;
    font-size: 3vw;
  }
  .answerq {
    // padding: 24px;
    position: relative;

    display: flex;
    flex-wrap: wrap;
    .returngo {
      position: absolute;
      left: 0;
      top: -51px;
    }

    background: #f7fbff;
    .topic {
      padding: 0 24px;
      width: 100%;
      margin-right: 0px;

      // background-color: #fff;
      .top-topic {
        height: auto !important;
        margin-bottom: 5px;
        line-height: 30px;
        font-weight: bold;
        font-size: 16px;
        color: #03305c;
        border-bottom: 1px solid #ededed;
        // background-color: #cf2727;
      }
    }
    .xuanxiang {
      margin-top: 24px;
      // background-color: #fff;
    }
    .topic-center {
      width: 100%;
      padding: 0 0px;
      // background-color: #fff;
    }
    .topic-righr {
      height: 81px;
      background-color: #fff;
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #ededed;
      font-weight: bold;
      font-size: 14px;
      color: #03305c;
      .topicon {
        line-height: 81px;
        font-size: 14px;
        color: #03305c;
        .spantext {
          font-weight: 500;

          color: #fb6d30;
        }
      }
    }
  }
  .time-cleck-green {
    width: 99%;
    background: #e6f7ef;
    border: 1px solid #0aaf60;
    font-weight: 400;
    font-size: 1vw;
    height: 34px;
    margin-top: 5px;
    line-height: 34px;
    color: #0aaf60;
  }
  .time-cleck-red {
    width: 99%;
    background: rgba(255, 85, 85, 0.1);
    border: 1px solid #ff5555;
    font-weight: 400;
    font-size: 1vw;
    height: 34px;
    margin-top: 5px;
    line-height: 34px;
    color: #ff5555;
  }
  .time-cleck-nube {
    width: 99%;
    // display: flex;
    margin-top: 5px;
    background: #f7fbff;
    height: 34px;
    line-height: 34px;
    width: 50%;
  }
  .time-cleck {
    width: 99%;
    box-sizing: border-box;
    margin-top: 5px;
    font-weight: 400;
    font-size: 1vw;
    color: #0075ff;
    border-radius: 4px;
    border: 1px solid #0075ff;
  }

  .timi {
    margin-top: 0px;
    // height: 100%;
    overflow: auto;
    /* WebKit 浏览器（Chrome、Safari） */
    scrollbar-width: none;
    -ms-overflow-style: none;
    // height: 75vh;

    .timi-p {
      font-family: DINAlternate, DINAlternate;
      font-weight: 500;
      font-size: 3vw;
      color: #03305c;
      margin-top: 1vw;
      line-height: 16px;
      text-align: left;
      font-style: normal;
    }
  }
  .answer {
    margin-top: 1.5vw;
    padding: 1px 1.3vw 1.5vw;
    font-weight: 700;
    background-color: #f7fbff;
    font-size: 13px;
    color: #03305c;
  }
}
</style>
